<?php
/**
 * Created by PhpStorm.
 * User: cat
 * Date: 2019/3/17
 * Time: 10:52
 */
/**
 * Code:-1 不明错误
 * Code：1 图片正常 返回码OK，PICID为新浪返回值
 * Code：2 用户Cookies失效
 * Code：3 空文件 Empty File
 */
include_once 'Utils/IoUtils/FileHelper.php';
include_once 'SinaUtils/SinaUpload.php';
include_once 'SinaUtils/SinaSiaticvalue.php';
include_once 'Utils/TextUtlis/TextHelper.php';
function UploadFile($FilePath)
{
    $result_value = array('code' => 0, 'pic_id' => '', 'tip' => '');//定义返回数组

    $SinaCookies = ReadAllText(SinaCookiesFile);

    if ($SinaCookies == '') {

	   return UserTokenInvalid($result_value);

    }

    $url = 'http://picupload.service.weibo.com/interface/pic_upload.php?ori=1&mime=image%2Fjpeg&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog';


    $curl = curl_init($url);

    $post['b64_data'] = @base64_encode(file_get_contents($FilePath));

    if ($post['b64_data'] == "") {
	   return Result($result_value,3, 'Empty File','');
    }

    curl_setopt_array($curl, array(
	   CURLOPT_POST => true,
//	   CURLOPT_VERBOSE => true,

	   CURLOPT_RETURNTRANSFER => true,//返回数据而不是直接输出
	   CURLOPT_HTTPHEADER => array("Cookie: $SinaCookies"),
	   CURLOPT_POSTFIELDS => $post,
    ));
    $output = curl_exec($curl);
    curl_close($curl);
    echo "\r\n----------------------------------------------------------\r\n";
    $output = ReplaceRegex($output, "(<.*?>.*?<\/.*?>|<.*?\/>)", '');
 echo  $output;//打印json返回结果

    $result_pretty = json_decode($output);

    if ($result_pretty->code == 'A00006') {
	   return Result($result_value,1,  $result_pretty->data->pics->pic_1->pid,'ok');

    } else if ($result_pretty->code == 'A20001') {
	   return UserTokenInvalid($result_value);
    }
    return Result($result_value,-1, 'unknown error','');


}

/***处理并返回提示用户cookies失效
 * @param $result_value
 * @return false|string
 */
function UserTokenInvalid($result_value)
{
    return Result($result_value,2, 'User token invalid','');

}

/***处理并返回相关结果
 * @param $result_value
 * @param $result_code
 * @param $result_tip
 * @param $result_pic_id
 * @return false|string
 */
function Result($result_value,$result_code,$result_tip,$result_pic_id){
    $result_value['tip'] = $result_tip;
    $result_value['code'] = $result_code;
    $result_value['pic_id'] = $result_pic_id;
    return json_encode($result_value);

}

?>